#include "dlg_diskfile.h"
#include "ui_dlg_diskfile.h"
dlg_DiskFile::dlg_DiskFile(QDialog *parent) :
    QDialog(parent),
    ui(new Ui::dlg_DiskFile),
    m_fileDialog(new QFileDialog(this)),
    m_imgFile(nullptr)
{
    ui->setupUi(this);
    //去掉边框
    this->setWindowFlags(Qt::FramelessWindowHint);
    //不使用标准文件对话框
    this->m_fileDialog->setOption(QFileDialog::DontUseNativeDialog);
    //去掉文件对话框边框
    this->m_fileDialog->setWindowFlag(Qt::FramelessWindowHint);
    //文件对话框返回存在的单个文件名
    this->m_fileDialog->setFileMode(QFileDialog::ExistingFile);
    //当鼠标停在该单元时气泡显示内容
    connect(ui->tab_fileInfo, &QTableWidget::itemEntered, this, [](QTableWidgetItem * item)->void {
        if(item == nullptr)return;
        QToolTip::showText(QCursor::pos(), item->text());
    });
}

dlg_DiskFile::~dlg_DiskFile()
{
    delete ui;
}

void dlg_DiskFile::initWidget()
{
    //初始化对话框模式
    this->initDialog();
    //初始化toolbutton
    this->initToolButton();
    //加载主题效果
    this->loadQss();
    //前进后退按钮默认都不可用（在选定/输入文件名之前）
    ui->btn_back->setEnabled(false);
    ui->btn_next->setEnabled(false);
    //清空文件名
    ui->lineEdit_filename->setText("");
    //重置按钮名称
    ui->btn_next->setText("继续>");
    //文件存在性判断重置
    ui->label_message->setText("");
    //设置默认文件路径
    ui->label_filepath->setText(sys_Data::getInstance()->getOpenDirHistory());
    //当前页为0
    ui->stackedWidget->setCurrentIndex(0);
}

void dlg_DiskFile::initToolButton()
{
    //给toolbutton增加选项
    QStringList filePathList = sys_Data::getInstance()->getOpenFileHistory();
    QMenu *menu = new QMenu;
    for(const auto& filePath  : filePathList) {
        QAction *action = new QAction(filePath, ui->tbtn_history);
        //toolbutton菜单被点击后触发的事件
        connect(action, &QAction::triggered, this, [&]() {
            QFileInfo info(qobject_cast<QAction*>(sender())->text());
            ui->label_filepath->setText(info.absolutePath());
            ui->lineEdit_filename->setText(info.fileName());
        });
        menu->addAction(action);
    }
    ui->tbtn_history->setMenu(menu);
    ui->tbtn_history->setPopupMode(QToolButton::InstantPopup);
}

void dlg_DiskFile::initDialog()
{
    ui->label_title->setText("打开主图像");
    this->m_fileDialog->setAcceptMode(QFileDialog::AcceptOpen);
    this->m_fileDialog->setNameFilter("(All Files) *.nii *.dcm");
}

void dlg_DiskFile::loadQss()
{
    QString style = sys_Data::getInstance()->getThemeQss();
    this->setStyleSheet(style);//设置主题样式
    this->m_fileDialog->setStyleSheet(style);//设置文件对话框主题样式
    ui->tbtn_history->menu()->setStyleSheet(style);//设置历史文件toolbutton样式
    foreach(QPushButton* btn, this->m_fileDialog->findChildren<QPushButton*>()) {
        btn->setFixedSize(80, 20);//设置文件对话框按钮大小
    }
}

void dlg_DiskFile::on_btn_back_clicked()
{
    ui->stackedWidget->setCurrentIndex(0);
    ui->btn_next->setText("继续>");
    ui->btn_back->setEnabled(false);
}


void dlg_DiskFile::on_btn_cancel_clicked()
{
    this->m_imgFile->clear();
    this->hide();
}


void dlg_DiskFile::on_btn_next_clicked()
{
    if(ui->btn_next->text() == "继续>" && this->parsingFile()) {
        ui->stackedWidget->setCurrentIndex(1);
        ui->btn_next->setText("完成");
        ui->btn_next->setEnabled(true);
        ui->btn_back->setEnabled(true);
    } else {
        this->hide();
    }
}

void dlg_DiskFile::on_btn_browse_clicked()
{
    this->m_fileDialog->setDirectory(ui->label_filepath->text());
    if(this->m_fileDialog->exec() == QFileDialog::AcceptSave) {
        QStringList fileName = this->m_fileDialog->selectedFiles();
        QFileInfo info(fileName.first());
        ui->label_filepath->setText(info.absolutePath());
        ui->lineEdit_filename->setText(info.fileName());
        ui->btn_next->setEnabled(true);
    }
}

void dlg_DiskFile::on_lineEdit_filename_textChanged()
{
    //输入框内容改变时触发，实时检测文件是否存在
    if(this->isExist(ui->label_filepath->text() + '/' + ui->lineEdit_filename->text())) {
        ui->label_message->setText("");
        ui->btn_next->setEnabled(true);
    } else {
        ui->label_message->setText("文件不存在");
    }
}

bool dlg_DiskFile::parsingFile()
{
    if(nullptr != this->m_imgFile) {
        this->m_imgFile->openFile(ui->label_filepath->text() + '/' + ui->lineEdit_filename->text());
        this->updateTable();
    }
    return true;
}

void dlg_DiskFile::updateTable()
{
    const img_Info &info = this->m_imgFile->info();//常量引用仅为方便书写
    ui->tab_fileInfo->setMouseTracking(true);//捕捉鼠标悬停事件
    ui->tab_fileInfo->clearContents();//清空表格内容
    //设置表头
    ui->tab_fileInfo->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tab_fileInfo->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Interactive);
    ui->tab_fileInfo->setColumnWidth(0, 80);
    uint8_t row = 0;//当前行计数
    // file name
    ui->tab_fileInfo->setItem(row, 0, new QTableWidgetItem("file name"));
    ui->tab_fileInfo->setItem(row++, 1, new QTableWidgetItem(info.fileName));
    // file size
    ui->tab_fileInfo->setItem(row, 0, new QTableWidgetItem("file size"));
    ui->tab_fileInfo->setItem(row++, 1, new QTableWidgetItem(QString("%1KB").arg(info.fileSize)));
    // dim info
    ui->tab_fileInfo->setItem(row, 0, new QTableWidgetItem("dim info"));
    ui->tab_fileInfo->setItem(row++, 1, new QTableWidgetItem(QString::number(info.dimInfo)));
    // dim[8]
    ui->tab_fileInfo->setItem(row, 0, new QTableWidgetItem(QString("dim[8]")));
    ui->tab_fileInfo->setItem(row++, 1, new QTableWidgetItem(
                                  QString("[ %1, %2, %3, %4, %5, %6, %7, %8 ]")
                                  .arg(info.dim[0]).arg(info.dim[1])
                                  .arg(info.dim[2]).arg(info.dim[3])
                                  .arg(info.dim[4]).arg(info.dim[5])
                                  .arg(info.dim[6]).arg(info.dim[7])));
    // pixdim[8]
    ui->tab_fileInfo->setItem(row, 0, new QTableWidgetItem(QString("pixdim[8]")));
    ui->tab_fileInfo->setItem(row++, 1, new QTableWidgetItem(
                                  QString("[ %1, %2, %3, %4, %5, %6, %7, %8 ]")
                                  .arg(info.pixdim[0]).arg(info.pixdim[1])
                                  .arg(info.pixdim[2]).arg(info.pixdim[3])
                                  .arg(info.pixdim[4]).arg(info.pixdim[5])
                                  .arg(info.pixdim[6]).arg(info.pixdim[7])));
    // vox offset
    ui->tab_fileInfo->setItem(row, 0, new QTableWidgetItem("vox offset"));
    ui->tab_fileInfo->setItem(row++, 1, new QTableWidgetItem(QString::number(info.voxOffset)));
    // data type
    ui->tab_fileInfo->setItem(row, 0, new QTableWidgetItem("data type"));
    ui->tab_fileInfo->setItem(row++, 1, new QTableWidgetItem(img_Info::DATA_TYPE[info.dataType]));
    // bit pix
    ui->tab_fileInfo->setItem(row, 0, new QTableWidgetItem("bit pix"));
    ui->tab_fileInfo->setItem(row++, 1, new QTableWidgetItem(QString::number(info.bitPix)));
    // scl slope
    ui->tab_fileInfo->setItem(row, 0, new QTableWidgetItem("scl slope"));
    ui->tab_fileInfo->setItem(row++, 1, new QTableWidgetItem(QString::number(info.sclSlope)));
    // scl inter
    ui->tab_fileInfo->setItem(row, 0, new QTableWidgetItem("scl inter"));
    ui->tab_fileInfo->setItem(row++, 1, new QTableWidgetItem(QString::number(info.sclInter)));
    // descrip
    ui->tab_fileInfo->setItem(row, 0, new QTableWidgetItem("descrip"));
    ui->tab_fileInfo->setItem(row++, 1, new QTableWidgetItem(info.descrip.isEmpty() ? "NULL" :
                              info.descrip.length() == 73 ? "分割文件" : info.descrip));
    // aux file
    ui->tab_fileInfo->setItem(row, 0, new QTableWidgetItem("aux file"));
    ui->tab_fileInfo->setItem(row++, 1, new QTableWidgetItem(info.auxFile.isEmpty() ? "NULL" : info.auxFile));
    // qform code
    ui->tab_fileInfo->setItem(row, 0, new QTableWidgetItem("qform code"));
    ui->tab_fileInfo->setItem(row++, 1, new QTableWidgetItem(QString::number(info.qFormCode)));
    // sform code
    ui->tab_fileInfo->setItem(row, 0, new QTableWidgetItem("sform code"));
    ui->tab_fileInfo->setItem(row++, 1, new QTableWidgetItem(QString::number(info.sFormCode)));
    // qoffset[3]
    ui->tab_fileInfo->setItem(row, 0, new QTableWidgetItem("qoffset[3]"));
    ui->tab_fileInfo->setItem(row++, 1, new QTableWidgetItem(QString("[ %1, %2, %3 ]")
                              .arg(info.qOffset[0]).arg(info.qOffset[1]).arg(info.qOffset[2])));
    // srow_x
    ui->tab_fileInfo->setItem(row, 0, new QTableWidgetItem("srow x"));
    ui->tab_fileInfo->setItem(row++, 1, new QTableWidgetItem(QString("[ %1, %2, %3, %4 ]")
                              .arg(info.srow[0][0]).arg(info.srow[0][1])
                              .arg(info.srow[0][2]).arg(info.srow[0][3])));
    // srow_y
    ui->tab_fileInfo->setItem(row, 0, new QTableWidgetItem("srow y"));
    ui->tab_fileInfo->setItem(row++, 1, new QTableWidgetItem(QString("[ %1, %2, %3, %4 ]")
                              .arg(info.srow[1][0]).arg(info.srow[1][1])
                              .arg(info.srow[1][2]).arg(info.srow[1][3])));
    // srow_z
    ui->tab_fileInfo->setItem(row, 0, new QTableWidgetItem("srow z"));
    ui->tab_fileInfo->setItem(row++, 1, new QTableWidgetItem(QString("[ %1, %2, %3, %4 ]")
                              .arg(info.srow[2][0]).arg(info.srow[2][1])
                              .arg(info.srow[2][2]).arg(info.srow[2][3])));
    // xyzt_units
    ui->tab_fileInfo->setItem(row, 0, new QTableWidgetItem("xyzt units"));
    ui->tab_fileInfo->setItem(row++, 1, new QTableWidgetItem(img_Info::UNIT[info.xyzt_units]));
    //重设置表格行数
    ui->tab_fileInfo->setRowCount(row);
}

bool dlg_DiskFile::isExist(const QString&fileName)
{
    return QFileInfo(fileName).isFile();
}

void dlg_DiskFile::openFile(img_File *imgFile)
{
    this->m_imgFile = imgFile;
    this->initWidget();
    this->exec();
    this->m_imgFile = nullptr;//放弃该对象的指针
}
